package wc.Dao.DaoImpl;

import wc.Dao.UserDao;
import wc.Utils.JdbcUtil;
import wc.domain.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:UserDaoImpl
 * @Author: 鹿建文
 * @Date: 2022/4/9  - 16:49
 * @Describe:
 */
public class UserDaoImpl implements UserDao {
    @Override
    public int selectCount() throws SQLException {
        int count = 0;
        Connection conn = JdbcUtil.getConnection();
        Statement stmt = conn.createStatement();
        String sql = "select count(*) count from tb_user";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            count = rs.getInt("count");
        }
        JdbcUtil.release(conn, stmt, rs);
        return count;
    }

    @Override
    public List<User> selectPage(Integer PageNumber, Integer PageSize) throws SQLException {
        ArrayList<User> res = new ArrayList<>();
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from tb_user limit ?, ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, (PageNumber - 1) * PageSize);
        ps.setInt(2, PageSize);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            boolean gender = rs.getBoolean("gender");
            String tel = rs.getString("tel");
            int credits = rs.getInt("credits");
            User user = new User(id, name, gender, tel, credits);
            res.add(user);
        }
        JdbcUtil.release(conn, ps, rs);
        return res;
    }
}
